package com.appspot.bibtable.model.format;

import java.util.Collection;

public class CollectionFormatter extends OutputFormatter
{
	public CollectionFormatter()
	{
		super();
	}

	public CollectionFormatter(OutputFormatter elementFormatter)
	{
		super(elementFormatter);
	}

	@Override
	public String format(Object collection)
	{
		return format((Collection<?>)collection);
	}

	public <T> String format(Collection<?> collection)
	{
		if (collection == null)
		{
			return null;
		}
		int count = collection.size();
		if (count == 0)
		{
			return null;
		}
		
		OutputFormatter elementFormatter = getElementFormatter();
		if (elementFormatter == null)
		{
			elementFormatter = new DefaultOutputFormatter();
		}

		StringBuilder builder = new StringBuilder();
		builder.append("[");
		for (Object object : collection)
		{
			String value = elementFormatter.format(object);
			builder.append(value);
			if (--count > 0)
			{
				builder.append("; ");
			}
		}
		builder.append("]");
		return builder.toString();
	}
}
